<template>
  <div class="container">
    <!-- 头部区域 -->
    <div class="header">
      <div class="logo">
        <i class="fas fa-user-circle"></i>
        UP主分析报告
      </div>
      <router-link to="/" class="btn btn-primary float-end"
                   style="background-color: #FB7299; border-color: #FB7299;
                   position: fixed;top: 10px;left: 10px;z-index: 1000;min-width: 80px;">
        主页
      </router-link>
    </div>
    <!-- UP主信息区域 -->
    <div class="creator-header">
      <div>
        <img :src="upInfo.pic" class="creator-avatar">
      </div>
      <div class="creator-info">
        <h2 class="creator-name">{{ upInfo.name }}</h2>
        <div class="creator-stats">
          <div class="stat-item">
            <div class="stat-value">{{ formatNumber(upInfo.followers) }}</div>
            <div class="stat-label">粉丝数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ formatNumber(upInfo.likes) }}</div>
            <div class="stat-label">获赞数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ upInfo.videos }}</div>
            <div class="stat-label">视频数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ formatNumber(upInfo.views) }}</div>
            <div class="stat-label">播放量</div>
          </div>
        </div>
      </div>
      <div class="btn btn-primary" v-if="!liked"
           style="background-color: #FB7299; border-color: #FB7299; margin-top: 150px;min-width: 80px"
           @click="doLike">
        关注
      </div>
      <div class="btn btn-primary" v-if="liked"
           style="background-color: #C3C3C3; border-color: #C3C3C3; margin-top: 150px;min-width: 80px"
           @click="doDislike">
        已关注
      </div>
    </div>


    <!-- 内容区域 -->
    <div class="content" >
      <!-- 粉丝变化图表 -->
      <div class="fans-chart-container">
        <LineChart
            :x-axis-data="formatted_time"
            :series-data="tendency_fans"
            :title="title"
            height="100%"
            @change-mode = "requestTrends"
        v-if="haveData"/>
        <span class="no-data" v-if="!haveData">
          还没有数据，可以先关注UP哟~
        </span>
      </div>
      <word-cloud :words="words"/>
    </div>
<!-- 视频列表 -->
      <div class="videos-container">
        <h3 class="section-title">
          <i class="fas fa-video"></i> 最新发布视频
        </h3>
        <div class="videos-list">
          <div class="video-item" v-for="video in videos" :key="video.id" @click="searchVideo(video.bvid)">
            <div>
              <img :src="video.pic" class="video-thumb">
            </div>
            <div class="video-info">
              <div class="video-title">{{ video.title }}</div>
              <div class="video-stats">
                <div class="video-stat">
                  <i class="fas fa-calendar"></i> {{ video.date }}
                </div>
                <div class="video-stat">
                  <i class="fas fa-eye"></i> {{ formatNumber(video.views) }}
                </div>
                <div class="video-stat">
                  <i class="fas fa-thumbs-up"></i> {{ formatNumber(video.likes) }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    <!-- 数据分析区域 -->

  </div>
  <router-view :key="$route.fullPath" />
</template>

<script setup>
import {ref, onMounted, watch, computed} from 'vue';
import LineChart from "@/components/LineChart.vue";
import {useUserStore} from "@/store/user.js";
import {getUpBasicInfo, getPublicInfo, getWordCloudInfo, getTrendsInfo,doLikeUp,cancelLikeUp,getLikeUp,checkCookie} from "@/api/user.js";
import {getVideoBasicInfo} from "@/api/video.js";
import {useRoute} from "vue-router";
import WordCloud from "@/components/WordCloud.vue";
import router from "@/router/index.js";

const title = ref('粉丝变化数据(每小时)');
const route = useRoute();
const words = ref([]);
const wordCache = ref([]);
const tendency_fans = ref([]);
const tendency_time = ref([]);
const formatted_time = ref([]); // 存储格式化后的时间(小时:分钟)
const haveData = ref(false);

const liked = ref(false);

const userInfo = useUserStore();
const upInfo = ref({
  id: '',
  name: '',
  followers: 0,
  likes: 0,
  videos: 0,
  views: 0,
  pic: null,
})

const searchVideo = async (bvid) =>{
  await router.push('/video/' + bvid);
}

const initUpInfo = async () => {
  try {
    const term = route.params.id;
    const respond = await getUpBasicInfo(term);
    console.log(respond.data)
    upInfo.value = {
      mid: respond.data.mid,
      name: respond.data.name,
      followers: respond.data.followers,
      likes: respond.data.likes,
      videos: respond.data.videos,
      views: respond.data.views,
      pic: '/api/proxy/img?url=' + respond.data.pic,
    }

    console.log(upInfo);
  } catch (error) {
    console.error('请求失败:', error);
  }
}

const initPublic = async () => {
  try {
    const term = route.params.id;
    const respond = await getPublicInfo(term);
    const res = respond.data;
    videos.value = [];
    console.log(res);
    const videoPromises = res.data.slice(0, 5).map(async (item, index) => {
      const videoRespond = await getVideoBasicInfo(item);
      const videoRes = videoRespond.data;
      const date = new Date(videoRes.data.pubdate * 1000);
      console.log(videoRes);
      return {
        id: index,
        bvid: videoRes.data.bvid,
        title: videoRes.data.title,
        views: videoRes.data.view,
        likes: videoRes.data.like,
        date: date.toLocaleString(),
        pic: '/api/proxy/img?url=' + videoRes.data.pic
      };
    });

    videos.value = await Promise.all(videoPromises);
  } catch (error) {
    console.error('请求失败:', error);
  }
}
//初始化趋势表
const initTrends = async () => {
  try {
    const term = route.params.id;
    const respond = await getTrendsInfo(term);
    const res = respond.data;
    const followers = res.data.map(item => item.follower);
    const timeList = res.data.map(item => item.date);
    tendency_fans.value = [...followers].reverse(); // 使用展开运算符避免修改原数组
    tendency_time.value = [...timeList].reverse();
    formatted_time.value = timeList
        .map(date => extractTime(date))
        .reverse();
    if (tendency_fans.value.length > 0){
      haveData.value = true;
    }

  } catch (error) {
    console.error('请求失败:', error);
  }
}
//请求趋势
const requestTrends = async (type) =>{
  try {
    const term = route.params.id;
    const respond = await getTrendsInfo(term,50,0,type);
    changeTitle(type);
    const res = respond.data;
    const followers = res.data.map(item => item.follower);
    const timeList = res.data.map(item => item.date);
    tendency_fans.value = [...followers].reverse(); // 使用展开运算符避免修改原数组
    tendency_time.value = [...timeList].reverse();
    formatted_time.value = timeList
        .map(date => extractTime(date))
        .reverse();
    if (tendency_fans.value.length > 0){
      haveData.value = true;
    }

  } catch (error) {
    console.error('请求失败:', error);
  }
}

const changeTitle = (type) =>{
  switch (type) {
    case '5_minute':
      title.value = '粉丝变化数据(每5分钟)';
      break;
    case 'hour':
      title.value = '粉丝变化数据(每小时)';
      break;
    case 'day':
      title.value = '粉丝变化数据(每天)';
      break;
  }
}

//处理时间
const extractTime = (dateStr) => {
  const date = new Date(dateStr);
  const month = date.getMonth() + 1; // 月份从0开始，需要+1
  const day = date.getDate();
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${month}.${day} ${hours}:${minutes}`;
};
//初始化词云
const initWordCloud = async () => {
  try {
    const term = route.params.id;
    const respond = await getWordCloudInfo(term);
    const res = respond.data;
    wordCache.value = res.data.slice(0, 15);
    words.value = wordCache.value;
  } catch (error) {
    console.error('请求失败:', error);
  }
}
//初始化关注
const initLikeUp = async () => {
  try {
    const term = route.params.id;
    const respond = await getLikeUp(userInfo.uid);
    const res = respond.data;
    res.data.mids.forEach(
        mid =>{
          if(mid === term){
            liked.value = true;
          }
        }
    )
  }catch (error){
    console.error('请求失败:', error);
  }
}
//处理关注
const doLike = async () => {
  try {
    console.log(route);
    const term = route.params.id;
    console.log(term);
    const data = {
      uid: userInfo.uid.toString(),
      mid: term,
    }
    const respond = await doLikeUp(data);
    const res = respond.data;
    if(res.code === 200){
      liked.value = true;
    }

  }catch (error){
    console.error('请求失败:', error);
  }
}
const doDislike = async () => {
  try {
    const term = route.params.id;
    const data = {
      uid: userInfo.uid.toString(),
      mid: term,
    }
    const respond = await cancelLikeUp(data);
    const res = respond.data;
    if(res.code === 200){
      liked.value = false;
    }
  }catch (error){
    console.error('请求失败:', error);
  }
}

const timeRange = ref(30);
// 视频列表数据
const videos = ref([]);
const formatNumber = (num) => {
  if (num >= 100000000) {
    return (num / 100000000).toFixed(1) + '亿';
  }
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万';
  }
  return num.toString();
};
const checkToken = async () => {
  if (userInfo.cookie !== '') {
    const respond = await checkCookie();
    if (respond.data.code === 200){
      console.log('in');
    }
    else{
      console.log('timeout');
      userInfo.logout();
    }
  } else {
    console.log('out');
    userInfo.logout();
    await router.push('/login');
  }
}
// 监听时间范围变化
watch(timeRange, () => {
  //initChart();
});

// 初始化
onMounted(async () => {
  await  checkToken();
  await Promise.all([
    initUpInfo(),
    initPublic(),
    initTrends(),
    initWordCloud(),
    initLikeUp(),
  ])
});
</script>

<style>
:root {
  --primary: #4361ee;
  --primary-light: #4895ef;
  --secondary: #3f37c9;
  --accent: #f72585;
  --success: #4cc9f0;
  --dark: #2b2d42;
  --light: #f8f9fa;
  --gray: #8d99ae;
  --card-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  --transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
}

body {
  background: linear-gradient(135deg, #f0f4ff 0%, #e6f0ff 100%);
  color: #333;
  min-height: 100vh;
  padding: 20px;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px 0;
}

.logo {
  font-size: 2.8rem;
  font-weight: 800;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  background: linear-gradient(135deg, var(--primary), var(--accent));
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.no-data {
  font-size: 30px; /* 调整字体大小 */
  color: #FB7299; /* 可选：调整文字颜色 */
}

.logo:hover {
  transform: translateY(-3px);
}

/* UP主信息卡片 */
.creator-header {
  background: white;
  border-radius: 24px;
  box-shadow: var(--card-shadow);
  padding: 30px;
  margin-bottom: 30px;
  display: flex;
  align-items: center;
  gap: 35px;
  transition: var(--transition);
  border: 1px solid #e6f0ff;
}

.creator-header:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.creator-avatar {
  width: 160px;
  height: 160px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 54px;
  font-weight: bold;
  color: var(--primary);
  background: #e6f0ff;
  border: 4px solid var(--primary);
  box-shadow: 0 10px 30px rgba(67, 97, 238, 0.25);
  transition: var(--transition);
  flex-shrink: 0;
}

.creator-header:hover .creator-avatar {
  transform: scale(1.05);
  box-shadow: 0 12px 35px rgba(67, 97, 238, 0.35);
}

.creator-info {
  flex: 1;
}

.creator-name {
  font-size: 42px;
  font-weight: 800;
  color: var(--dark);
  margin-bottom: 18px;
  background: linear-gradient(135deg, var(--primary), var(--dark));
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  transition: var(--transition);
}

.creator-header:hover .creator-name {
  background: linear-gradient(135deg, var(--accent), var(--dark));
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

.creator-stats {
  display: flex;
  gap: 35px;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 18px 25px;
  background: #f7faff;
  border-radius: 16px;
  min-width: 150px;
  border: 1px solid #e6f0ff;
  box-shadow: 0 8px 20px rgba(67, 97, 238, 0.15);
  transition: var(--transition);
  position: relative;
  overflow: hidden;
}

.stat-item::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: var(--primary);
}

.stat-item:hover {
  transform: translateY(-8px);
  box-shadow: 0 15px 35px rgba(67, 97, 238, 0.2);
}

.stat-value {
  font-size: 30px;
  font-weight: 800;
  color: var(--accent);
  margin-bottom: 5px;
  transition: var(--transition);
}

.stat-item:hover .stat-value {
  color: var(--primary);
}

.stat-label {
  font-size: 16px;
  color: var(--gray);
  font-weight: 600;
}


.panel-title i {
  color: var(--accent);
}

/* 内容区域 */
.content {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
}

/* 粉丝变化图表 */
.fans-chart-container {
  flex: 2;
  background: white;
  border-radius: 20px;
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  box-shadow: var(--card-shadow);
  padding: 30px;
  transition: var(--transition);
  border: 1px solid #e6f0ff;
  height: 500px;
}

.chart-title i {
  color: var(--accent);
}

/* 视频列表 */
.videos-container {
  flex: 1;
  background: white;
  border-radius: 20px;
  box-shadow: var(--card-shadow);
  padding: 30px;
  transition: var(--transition);
  border: 1px solid #e6f0ff;
  height: 500px;
  overflow-y: auto;
}

.videos-container:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 22px;
  font-weight: 700;
  margin-bottom: 25px;
  color: var(--primary);
  display: flex;
  align-items: center;
  gap: 12px;
}

.section-title i {
  color: var(--accent);
}

.videos-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.video-item {
  display: flex;
  gap: 15px;
  padding: 15px;
  border-radius: 16px;
  background: #f8fbff;
  border: 1px solid #e6f0ff;
  transition: var(--transition);
  cursor: pointer;
}

.video-item:hover {
  background: #edf3ff;
  transform: translateX(5px);
  box-shadow: 0 5px 15px rgba(67, 97, 238, 0.1);
}

.video-thumb {
  width: 120px;
  height: 70px;
  border-radius: 10px;
  background: linear-gradient(135deg, #e0e7ff 0%, #d1e3ff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--primary);
  font-size: 12px;
  font-weight: 600;
  flex-shrink: 0;
  position: relative;
}

.video-thumb::before {
  content: "视频";
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1;
}

.video-info {
  flex: 1;
}

.video-title {
  font-size: 16px;
  font-weight: 700;
  margin-bottom: 8px;
  color: var(--dark);
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.video-stats {
  display: flex;
  gap: 15px;
  font-size: 13px;
  color: var(--gray);
}

.video-stat {
  display: flex;
  align-items: center;
  gap: 4px;
}

.analysis-title i {
  color: var(--accent);
}


/* 响应式设计 */
@media (max-width: 992px) {
  .content {
    flex-direction: column;
  }

  .creator-header {
    flex-direction: column;
    text-align: center;
  }

  .creator-stats {
    justify-content: center;
  }

  .fans-chart-container, .videos-container {
    height: auto;
  }
}

@media (max-width: 768px) {
  .logo {
    font-size: 2.2rem;
  }

  .creator-name {
    font-size: 32px;
  }

  .stat-item {
    min-width: 120px;
    padding: 15px;
  }

  .stat-value {
    font-size: 24px;
  }
}
</style>